<?php
declare (strict_types = 1);

namespace app\lib;

use Firebase\JWT\JWT as JWTApi;
use think\Exception;

class Jwt
{
    public static function encode($uid){
        $config=config('jwt');

        $tokenData=[
            'iss'=>$config['iss'],
            'sub'=>$uid,
            'iat' => time(),//签发时间
            'nbf' => time(),//生效时间,
            'exp' => time()+$config['exp']
        ];
        $privateKey=file_get_contents($config['privateKey']);
       return JWTApi::encode(
           $tokenData,
           $privateKey,
           'RS256'
        );
    }


    public static function decode($token){
        try{
            $config=config('jwt');
            JWTApi::$leeway=$config['leeway'];
            $decoded=JWTApi::decode($token,file_get_contents($config['publicKey']),['RS256']);
            $decoded_array = (array) $decoded;
            //校验签发者
            if ($config['iss']!==$decoded_array['iss']){
                throw new Exception('无效Token',10001);
            }

            return $decoded_array['sub'];
        }catch (\Exception $exception){
            throw new Exception($exception->getMessage(),10002);
        }


    }
}